package cn.icanci.ladybird.controller;

import cn.icanci.ladybird.common.result.JsonData;
import cn.icanci.ladybird.common.util.security.JWTUtils;
import cn.icanci.ladybird.pojo.bo.UserLoginByCodeBO;
import cn.icanci.ladybird.pojo.bo.UserLoginByUsernameAndPasswordBO;
import cn.icanci.ladybird.pojo.bo.UserRegisterBO;
import cn.icanci.ladybird.pojo.bo.UserResetPwdBO;
import cn.icanci.ladybird.pojo.entity.UserInfo;
import cn.icanci.ladybird.service.UserInfoService;
import cn.icanci.ladybird.service.user.UserLoginService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: icanci
 * @date: Created in 2020/10/8 9:10
 * @classAction: 用户登录注册控制层
 */
@Controller
@Slf4j
@RequestMapping("/api/v1/pri/user/do")
public class UserController {

    @Autowired
    private UserIndexController userIndexController;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private UserInfoService userInfoService;

    /**
     * ===============================================
     * 单纯处理页面跳转
     * ===============================================
     */
    @GetMapping("/login-by-account")
    public String loginByAccount() {
        return "user/login-by-account";
    }

    @GetMapping("/login-by-code")
    public String loginByCode() {
        return "user/login-by-code";
    }

    @GetMapping("/register")
    public String register() {
        return "user/register";
    }

    @GetMapping("/reset-pwd")
    public String resetPassword() {
        return "user/reset-pwd";
    }

    @GetMapping("/logout")
    public String logout(Model model, HttpServletRequest request) {
        // 删除Token
        request.getSession().removeAttribute("token");
        // 删除 用户信息
        request.getSession().removeAttribute("user_id");
        // 返回首页
        return userIndexController.getUserIndexJson(model);
    }

    @GetMapping("/personal")
    public String personal(Model model, HttpServletRequest request) {
        // 查询个人的信息
        Long userId = Long.valueOf(request.getSession().getAttribute("user_id").toString());
        if (null == userId) {
            // 返回到登录界面
            return loginByAccount();
        } else {
            UserInfo userInfo = userInfoService.queryById(userId);
            if (null != userInfo) {
                JsonData jsonData = JsonData.builderSuccess(userInfo);
                model.addAttribute("jsonData", jsonData);
                return "user/personal";
            } else {
                return loginByAccount();
            }
        }
    }

    /**
     * ===============================================
     * 处理接收表单数据跳转
     * ===============================================
     */
    @PostMapping("/login-by-account-data")
    public String loginByAccountData(Model model, HttpServletRequest request, HttpServletResponse response, UserLoginByUsernameAndPasswordBO userLoginByUsernameAndPasswordBO) throws IOException {
        String token = userLoginService.queryByUserLoginByUsernameAndPasswordBO(userLoginByUsernameAndPasswordBO);
        if (StringUtils.isBlank(token)) {
            // 是空
            return loginByAccount();
        } else {
            // 不是空
            // 向 session 设置 token
            log.info("UserController.loginByAccountData - " + token);
            initPageIndex(token, request, response);
            // 返回首页
            return userIndexController.getUserIndexJson(model);
        }
    }

    @PostMapping("/login-by-code-data")
    public String loginByCodeData(Model model, HttpServletRequest request, HttpServletResponse response, UserLoginByCodeBO userLoginByCodeBO) throws IOException {
        log.info("UserController.loginByCodeData - " + userLoginByCodeBO);
        // 处理用户根据Code登录的请求
        JsonData jsonData = userLoginService.loginByCodeData(userLoginByCodeBO);
        if (jsonData.getCode().equals(-1)) {
            // 登录失败
            model.addAttribute("msg", jsonData.getMsg());
            return loginByCode();
        } else {
            String token = jsonData.getData().toString();
            log.info("UserController.loginByAccountData - " + token);
            initPageIndex(token, request, response);
            // 返回首页
            return userIndexController.getUserIndexJson(model);
        }
    }

    @PostMapping("/register-data")
    public String registerData(Model model, UserRegisterBO userRegisterBO) {
        log.info("UserController.registerData " + userRegisterBO);
        JsonData jsonData = userLoginService.userRegister(userRegisterBO);
        if (null == jsonData || jsonData.getCode().equals(-1)) {
            // 注册失败
            log.info("UserController.registerData");
            log.info(jsonData.toString());
            model.addAttribute("msg", "注册失败");
            return register();
        } else {
            // 注册成功
            return loginByAccount();
        }
    }

    @PostMapping("/reset-pwd-data")
    public String resetPasswordData(Model model, UserResetPwdBO userResetPwdBO) {
        log.info("UserController.resetPasswordData - 修改密码" + userResetPwdBO);
        JsonData jsonData = userLoginService.resetPassword(userResetPwdBO);
        if (jsonData.getCode().equals(-1)) {
            // 失败
            model.addAttribute("msg", jsonData.getMsg());
            return resetPassword();
        } else {
            return loginByAccount();
        }
    }

    @GetMapping("/personal-data")
    public String personalData(Model model, HttpServletRequest request) {
        // TODO 更新个人的信息 此部分没做 非核心功能
        return "user/personal";
    }

    /**
     * ===============================================
     * 页面数据初始化操作
     * ===============================================
     */

    /**
     * 初始化界面参数
     *
     * @param accessToken token
     * @param request     请求
     * @param response    响应
     * @throws IOException 异常对象
     */
    private void initPageIndex(String accessToken, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Claims claims = JWTUtils.checkJWT(accessToken);
        if (null == claims) {
            // 跳转到登录界面
            response.sendRedirect("/api/v1/pri/user/do/login-by-account");
        }

        String userHeadImg = String.valueOf(claims.get("user_head_img"));
        Long userId = Long.valueOf(claims.get("user_id").toString());
        String username = String.valueOf(claims.get("username"));
        Integer userEnabled = Integer.valueOf(claims.get("user_enabled").toString());
        // 判断用户的权限
        // 等于0就是没有权限
        if (userEnabled.equals(0)) {
            response.sendRedirect("/api/v1/pub/user/no-authority");
        }
        // 拥有权限
        HttpSession session = request.getSession();
        session.setAttribute("user_head_img", userHeadImg);
        session.setAttribute("user_id", userId);
        session.setAttribute("username", username);
        session.setAttribute("user_enabled", userEnabled);
        session.setAttribute("token", accessToken);
        // 设置过期时间为十分钟
        session.setMaxInactiveInterval(60 * 10);
        // 设置Token到Cookie
        Cookie cookie = new Cookie("token", accessToken);
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }
}
